<template>
  <div>
    <div>
      <el-table-form ref="form" :model="query">
        <el-form-item :table-form-merge="1.5" class="merge-item">
          <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
            <el-option label="下单时间" value="transactTime" />
            <el-option label="派单时间" value="dispatchFailTime" />
          </el-select>
          <el-date-picker
            v-show="swich==='map'"
            v-model="query.date1"
            type="date"
            unlink-panels
            placeholder="选择日期"
            :clearable="false"
            value-format="yyyy-MM-dd"
          />
          <el-date-picker
            v-show="swich==='form'"
            v-model="query.date"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="true"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="所属机构:" class="merge-item" :table-form-merge="1.5">
          <el-tree-select
            v-model="query.orgSNNo"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
            @node-click="selectTreeChange"
          />
          <div style="width: 120px; padding-left: 20px;">
            <el-checkbox v-model="query.option" label="包含下级" />
          </div>
        </el-form-item>
        <el-form-item label="派单方式:" :table-form-merge="1.2">
          <!-- <span>
            <el-tooltip placement="top">
              <div slot="content">
                自动派单：系统自动派出去的订单（优先级最高），只要系统自动派单成功了，就把这个订单的派单记录改为 自动派单（如果这个订单先手动派单成功，后面自动派单成功了，这个订单算自动派单）<br>
                手动派单： 在智能派单里面，手动派出去的订单、其他页面手动转派成功的订单（如果这个订单先自动派单成功，后面手动转派成功，这个订单算自动派单）<br>
                呼叫中心派单：呼叫中心下单时直接选择处理人为配送员的订单（非调度）<br>
                话务派单：话务下单时直接选择处理人为配送员的订单（非调度）<br>
                门店派单：门店下单时直接选择处理人为配送员的订单（非调度）<br>
                代客下单派单：在运气到家上面下单直接系统会直接把订单派给代客下单的配送员
              </div>
              <i class="el-icon-question" style="width: none;" />
            </el-tooltip>
          </span> -->
          <el-select v-model="query.dispatchType" style="width: 90%;" clearable placeholder="请选择">
            <el-option
              v-for="item in dispatchTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="派单状态:">
          <el-select v-model="query.dispatchStatus" clearable placeholder="请选择">
            <el-option
              v-for="item in [{desc:'派单成功',value:0},{desc:'派单失败',value:1}]"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="失败原因:">
          <el-select v-model="query.dispatchFailReason" clearable placeholder="请选择">
            <el-option
              v-for="item in reasonMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人:">
          <!-- <el-input v-model.trim="query.transactor" placeholder="请输入" clearable /> -->
          <el-select v-model="query.ownerIdList" multiple collapse-tags :loading="$loadingPlugin.getOwnerList" style="width: 100%;" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in ownerList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单号:">
          <el-input v-model.trim="query.orderCode" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="订单状态:">
          <el-select v-model="query.orderStatus" clearable placeholder="请选择">
            <el-option
              v-for="item in orderStatusMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-button v-permission="[40302, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button
            v-permission="[40302, 3]"
            :loading="$loadingPlugin.exportFile"
            type="primary"
            icon="el-icon-download"
            @click="exportFile"
          >导出</el-button>
        </template>
      </el-table-form>
    </div>
    <div style="display: flex; margin-bottom: 10px;">
      <el-link v-permission="[40302, 2]" :underline="false" style=" font-size: 16px; color: #126edc;" class="btn" size="mini" @click="cut"><i style="transform: rotate(-90deg);" class="el-icon-sort" />&nbsp;{{ swich==="form"?'切换为地图模式':'切换为表格模式' }}</el-link>
      <div v-if="swich==='map'" class="btnInfo">
        <img src="@/assets/map_images/blue_sprite.png">
        <span>派单成功</span>
        <img src="@/assets/map_images/red_sprite.png">
        <span>派单失败</span>
      </div>
    </div>
    <lb-table
      v-show="swich==='form'"
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      class="left"
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      :immediate-fetch="false"
      @fetch="fetchData"
    />
    <div v-if="swich==='map'" class="left">
      <!-- scroll-wheel-zoom：是否可以用鼠标滚轮控制地图缩放 -->
      <div class="name-box"><el-checkbox v-model="showName">显示名称</el-checkbox></div>
      <baidu-map
        ref="map"
        :key="updateMap"
        :map-click="false"
        style="height: 710px;"
        :enable-drawing-tool="true"
        scroll-wheel-zoom
        class="order_map"
        :center="center"
        :zoom="10"
        @ready="handler"
      >
        <template v-if="showName">
          <template v-if="fenceData.length">
            <!-- <bm-marker v-for="(item,index) in fenceData" :key="index" :position="{lng: item.longitude, lat: item.latitude}" :icon="markerIcon" :dragging="false"> -->
            <bm-label v-for="item in fenceData" :key="item.id" :position="{lng: item.longitude, lat: item.latitude}" :title="item.fenceName" :content="item.fenceName" :label-style="{color: 'blue', fontSize : '14px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
            <!-- </bm-marker> -->
          </template>
          <template v-if="fenceData1.length">
            <!-- <bm-marker v-for="(item,index) in fenceData1" :key="index" :position="{lng: item.longitude, lat: item.latitude}" :icon="markerIcon" :dragging="false"> -->
            <bm-label v-for="item in fenceData1" :key="item.id" :position="{lng: item.longitude, lat: item.latitude}" :title="item.fenceName" :content="item.fenceName" :label-style="{color: 'red', fontSize : '12px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
            <!-- </bm-marker> -->
          </template>
        </template>
      </baidu-map>
    </div>
    <csm-detail
      ref="csmDetail"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
  </div>
</template>

<script>
  import { queryExportDomain, exportOrderAutoDispatch, queryCsmTypeMap, queryMap, orderAutoDispatchList, queryTransactorList, selectUserFence, csDeliverUserList } from '@/api'
  import { parseTime, formatColumnMap, formatDate } from '@/utils'
  import { orderStatusObj } from '@/utils/map'
  import getTreeData from '@/utils/jsonTree'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  import OrderDetail from '@/views/orderCenter/orderManage/components/OrderDetails'
  import moment from 'dayjs'
  import { mapGetters } from 'vuex'
  var redIcon = require('@/assets/map_images/red_sprite.png')
  var blueIcon = require('@/assets/map_images/blue_sprite.png')
  export default {
    name: '',
    components: {
      CsmDetail,
      OrderDetail
    },
    data() {
      return {
        swich: 'form',
        transactorList: [], // 处理人列表
        calcTypeList: [],
        paymenFilList: [],
        orderFlagMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        orderSourceMap: [],
        csmTypeMapList: [],
        orderStatusMap: [],
        treeData: [],
        reasonMap: [], // 失败原因枚举
        dispatchTypeMap: [],
        dateType: 'dispatchFailTime',
        ownerList: [],
        query: {
          date: [],
          date1: '',
          dispatchFailReason: null,
          dispatchStatus: null,
          orgSNNo: null,
          orderCode: null,
          ownerIdList: '',
          transactor: '',
          option: false
        },
        zoom: 3,
        map: null,
        updateMap: 0,
        center: '',
        showName: true,
        fenceData: [],
        fenceData1: [],
        tableData1: [],
        mapParams: null,
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              align: 'center',
              fixed: true,
              width: 40
            },
            {
              prop: 'orderCode',
              label: '单号',
              align: 'center',
              width: 90,
              fixed: true,
              render: (h, { row }) => (
                row.orderCode ? <el-link underline={false} onClick={() => this.openBill(row)}>
                  {row.orderCode}
                </el-link> : <span>{row.orderCode}</span>
              )
            },
            {
              prop: 'csmAddress',
              label: '地址',
              width: 300,
              showOverflowTooltip: true
            },
            {
              prop: 'goodsCount',
              label: '商品数量',
              align: 'right',
              width: 80
            },
            {
              prop: 'orgName',
              label: '归属机构',
              showOverflowTooltip: true
            },
            {
              prop: 'goodsDesc',
              label: '商品描述',
              showOverflowTooltip: true,
              width: 180
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              width: 105,
              showOverflowTooltip: true,
              render: (h, { row }) => row.csmCode ? <el-link underline={false} onClick={() => this.openCsm(row)}>{row.csmCode}</el-link> : <span>{row.csmCode}</span>
            },
            {
              prop: 'csmName',
              label: '客户名称',
              width: 100
            },
            {
              prop: 'contactPhone',
              label: '客户电话',
              width: 110
            },
            {
              prop: 'transactor',
              label: '下单人',
              width: 110
            },
            {
              prop: 'transactTime',
              label: '下单时间',
              width: 180,
              render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            // {
            //   prop: 'appointmentDt',
            //   label: '配送时效区间',
            //   width: 180,
            //   render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            // },
            {
              prop: 'csmType',
              label: '客户类型',
              render: (h, { row }) => <span>{row.csmType ? formatColumnMap(this.csmTypeMapList, 'value', row.csmType, 'desc') : '' }</span>
            },
            {
              prop: 'bindDriverName',
              label: '绑定司机',
              showOverflowTooltip: true
            },
            {
              prop: 'ownerName',
              label: '处理人',
              width: 110
            },
            {
              prop: 'driverName',
              label: '大车司机',
              showOverflowTooltip: true
            },
            {
              prop: 'escortName',
              label: '押运员',
              showOverflowTooltip: true
            },
            {
              prop: 'orderStatus',
              label: '订单状态',
              width: 80,
              render: (h, { row }) => (
                    <span style={orderStatusObj[row.orderStatus]}>
                    {row.orderStatus &&
                    formatColumnMap(this.orderStatusMap, 'value', row.orderStatus, 'desc')}
                    </span>
                )
            },
            {
              prop: 'strategyType',
              label: '派单策略',
              width: 120,
              showOverflowTooltip: true
            },
            {
              prop: 'currentStrategyType',
              label: '执行策略',
              width: 120,
              showOverflowTooltip: true
            },
            {
              prop: 'dispatchStatus',
              label: '派单状态',
              width: 80,
              render: (h, { row }) => <span style={row.dispatchStatus ? 'color:#ff4949' : 'color:#13ce66'}>{row.dispatchStatus ? '失败' : '成功' }</span>
            },
            {
              prop: 'dispatchType',
              label: '派单方式',
              width: 110,
              showOverflowTooltip: true,
              render: (h, { row }) => <span >{row.dispatchType ? formatColumnMap(this.dispatchTypeMap, 'value', row.dispatchType, 'desc') : '' }</span>
            },
            {
              prop: 'dispatchFailReason',
              label: '失败原因',
              width: 150,
              showOverflowTooltip: true,
              render: (h, { row }) => <span>{row.dispatchFailReason ? formatColumnMap(this.reasonMap, 'value', row.dispatchFailReason, 'desc') : '' }</span>
            },
            {
              prop: 'dispatchFailTime',
              label: '派单时间',
              width: 160,
              render: (h, { row }) => <span>{ row.dispatchFailTime && parseTime(row.dispatchFailTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo', 'corpSettingData'
      ])
    },
    watch: {
      // 'mapParams': {
      //   async handler(newVal, oldVal) {
      //     // console.log(newVal, oldVal)
      //     if (this.swich === 'map') {
      //       const res = await orderAutoDispatchList({ ...this.mapParams, currentPage: 1, pageSize: 9999 })
      //       this.tableData1 = res.data.rows
      //     }
      //   },
      //   deep: true,
      //   immediate: true
      // }
    },
    async created() {
      await Promise.all([this.getExportDomain(), this.getTimeFn(), this.queryOptionsMap(), this.getCsmType(), this.getTreeData()])
      this.$refs.lbTable.fetch({ currentPage: 1 })
      const companyInfo = JSON.parse(sessionStorage.getItem('companyInfo'))
      // console.log('companyInfo', companyInfo )
      if (companyInfo) {
        this.center = companyInfo.city || '北京'
      }
    },
    mounted() {},
    methods: {
      getTimeFn() {
        const start = new Date()
        const end = new Date()
        this.query.date[0] = formatDate(start, 'yyyy-MM-dd') + ' 00:00:00'
        this.query.date[1] = formatDate(end, 'yyyy-MM-dd') + ' 23:59:59'
        this.query.date1 = formatDate(start, 'yyyy-MM-dd')
      },
      // 查询字典枚举
      async queryOptionsMap() {
        const [res1, res4, res5, res6, res7, res8, res9, res10] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'DispatchOrderFailReasonEnum' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' }),
          mergeAsyncFunc(queryMap, { enumName: 'DispatchTypeEnum' })
        ])
        this.reasonMap = res1.data // 失败原因枚举
        this.calcTypeList = res4.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res5.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.orderStatusMap = res6.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res7.data // 订单类型
        this.payStatusMap = res8.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.orderSourceMap = res9.data // 订单来源
        this.dispatchTypeMap = res10.data
        this.getTransactorList()
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      // 获取处理人列表
      async getOwnerList() {
        const orgId = this.currentOrg ? this.currentOrg.orgId : 0
        if (orgId) {
          const res = await csDeliverUserList({ deliveryOrgId: orgId })
          this.ownerList = res.data
        } else {
          this.ownerList = []
        }
      },
      // 机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.userInfo.orgSNNo
        this.query.orgId = this.userInfo.orgId
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const params = {
          currentPage,
          pageSize,
          ...this.query
        }
        if (this.query.date.length === 2 && this.swich === 'form') {
          if (this.dateType === 'transactTime') {
            params['transactTime'] = this.query.date[0]
            params['transactTimeEnd'] = this.query.date[1]
          }
          if (this.dateType === 'dispatchFailTime') {
            params['dispatchFailTimeStart'] = this.query.date[0]
            params['dispatchFailTimeEnd'] = this.query.date[1]
          }
        }
        if (this.query.date.length === 2 && this.swich === 'form' && moment(this.query.date[1]).diff(moment(this.query.date[0]), 'days') > 93) {
          this.$message.error('时间查询条件相差不能超过3个月')
          return
        }
        if (this.query.date1 && this.swich === 'map') {
          if (this.dateType === 'transactTime') {
            params['transactTime'] = this.query.date1 + ' 00:00:00'
            params['transactTimeEnd'] = this.query.date1 + ' 23:59:59'
          }
          if (this.dateType === 'dispatchFailTime') {
            params['dispatchFailTimeStart'] = this.query.date1 + ' 00:00:00'
            params['dispatchFailTimeEnd'] = this.query.date1 + ' 23:59:59'
          }
        }
        delete params.date
        delete params.date1
        if (this.swich === 'map') params.pageSize = 9999
        params.orgId = this.query.option ? 0 : this.query.orgId
        this.mapParams = params
        const res = await orderAutoDispatchList(params)
        if (res.data) {
          if (this.swich === 'form') {
            this.tableData.data = res.data.rows
            if (currentPage === 1) this.tableData.total = res.data.total
          } else {
            this.tableData1 = res.data.rows
          }
        }
        await this.updateMap++
      },
      parseTime,
      // 查询
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
        if (this.query.orgId && this.map) {
          setTimeout(() => {
            this.chooseOrg(this.query.orgId)
          }, 1000)
        }
      },
      async getCsmType() {
        const res = await queryCsmTypeMap()
        this.csmTypeMapList = res.data
      },
      async openBill(row) {
        await this.$refs.orderDetail.open(row, true)
      },
      // 打开客户
      async openCsm(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      async cut() {
        if (this.swich === 'form') {
          this.swich = 'map'
          this.$refs.lbTable.fetch({ currentPage: 1 })
        } else {
          this.swich = 'form'
          this.$refs.lbTable.fetch({ currentPage: 1 })
        }
      },
      async handler({ BMap, map }) {
        this.map = map
        const vm = this
        // var poi = new BMap.Point(116.307852, 40.057031)
        // map.centerAndZoom(poi, 16)
        var overlays = []
        vm.orderPointMarkers = [] // 初始化点

        var data = vm.tableData1
        // console.log(data)
        if (data.length > 0) {
          for (var x = 0; x < data.length; x++) {
            if (!(data[x].lon * 1) || !(data[x].lat * 1)) {
              continue
            }
            // 设置覆盖物图标
            var icon = new BMap.Icon(blueIcon, new BMap.Size(19, 25))
            if (data[x].dispatchStatus) {
              icon.imageUrl = redIcon
            } else {
              icon.imageUrl = blueIcon
            }
            // 是否选中
            icon.bean = data[x]
            var pt = new BMap.Point(data[x].lon, data[x].lat)
            var marker = new BMap.Marker(pt, { icon: icon })
            // 表示障碍物 没有点击
            // icon.imageUrl = "/image/map/marker_red_sprite.png";
            var template = "<span style='margin-right: 20px;height: 28px;display:inline-block;width: 200px;'>订&ensp;单&ensp;号： {0}</span><span style='margin-left: 155px;height: 28px;display:inline-block;'> 客户编号： {1}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>所属机构： {9}</span><span style='margin-left: 158px;height: 28px;display:inline-block;'>距离： {10}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;width: 200px;'>联&ensp;系&ensp;人： {2}</span><span style='margin-left: 155px;height: 28px;display:inline-block;'>联系电话： {3}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>地&ensp;&ensp;&ensp;&ensp;址： {4}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>商品描述： {5}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>下单时间： {6}</span><span style='height: 28px;display:inline-block;'>预约时间： {11}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>订单状态： {7}</span><span style='margin-left: 100px;height: 28px;display:inline-block;'>配送员： {12}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>派单状态： {8}</span><span style='margin-left: 115px;height: 28px;display:inline-block;'>失败原因： {13}</span><br/>"
            marker.orderCode = data[x].orderCode || ''
            marker.csmCode = data[x].csmCode || ''
            marker.contact = data[x].contact || ''
            marker.contactPhone = data[x].contactPhone || ''
            marker.csmAddress = data[x].csmAddress || ''
            marker.goodsDesc = data[x].goodsDesc || ''
            marker.transactTime = vm.parseTime(data[x].transactTime, '{y}-{m}-{d} {h}:{i}:{s}') || ''
            marker.submitParam = { orderCode: data[x].orderCode, ownerId: data[x].ownerId, ownerName: data[x].ownerName }
            marker.orderStatus = data[x].orderStatus ? formatColumnMap(vm.orderStatusMap, 'value', data[x].orderStatus, 'desc') : ''
            marker.dispatchStatus = data[x].dispatchStatus ? '失败' : '成功'
            marker.orgName = data[x].orgName
            marker.distance = (Number(data[x].distance) / 1000).toFixed(2) + 'km'
            marker.preOwnerName = data[x].ownerName
            marker.appointmentDt = data[x].appointmentDt && data[x].dateTimeSpare1 ? parseTime(data[x].appointmentDt, '{y}-{m}-{d} {h}:{i}:{s}') + ' 至 ' + parseTime(data[x].dateTimeSpare1, '{h}:{i}:{s}') : ''
            marker.dispatchFailReason = data[x].dispatchFailReason ? formatColumnMap(vm.reasonMap, 'value', data[x].dispatchFailReason, 'desc') : ''

            marker.addEventListener('mouseover', function() {
              var content = String.format(template, this.orderCode, this.csmCode, this.contact, this.contactPhone, this.csmAddress, this.goodsDesc, this.transactTime, this.orderStatus, this.dispatchStatus, this.orgName, this.distance, this.appointmentDt, this.preOwnerName, this.dispatchFailReason)
              var tempInfoWindow = new BMap.InfoWindow(content, {
                width: 600, // 信息窗口宽度
                height: 220, // 信息窗口高度
                title: '', // 信息窗口标题
                enableMessage: true// 设置允许信息窗发送短息
              })
              this.openInfoWindow(tempInfoWindow)
            })
            marker.addEventListener('mouseout', function() {
              this.closeInfoWindow()
            })

            marker.addEventListener('click', function(e) {
              // eslint-disable-next-line no-unused-vars
              var icon = this.getIcon()
              // 更新数量
            })
            // marker.setAnimation(BMAP_ANIMATION_BOUNCE) // 跳动的动画
            // 增加点
            map.addOverlay(marker) // 将标注添加到地图中
            // 存储所有marker
            vm.orderPointMarkers.push(marker)
          }
          // console.log(vm.orderPointMarkers)
        }
        // eslint-disable-next-line no-unused-vars
        var overlaycomplete = function(e) {
          overlays.push(e.overlay)
          switch (e.drawingMode) {
          // 图像标注
          case 'marker':break
          // 线的样式
          case 'polyline':

            break
          // 圆
          case 'circle':
            break
          // 多边形
          case 'polygon':
            break
          // 矩形
          case 'rectangle':
            var data = vm.tableData1
            if (data.length > 0) {
              for (var x = 0; x < data.length; x++) {
                if (data[x].lon === undefined || data[x].lat === undefined) {
                  continue
                }
                var pt = new BMap.Point(data[x].lon, data[x].lat)
                // 矩形  或  多边形
                if (window.BMapLib.GeoUtils.isPointInPolygon(pt, e.overlay)) {
                  var markers = vm.orderPointMarkers
                  if (markers.length > 0) {
                    for (var a = 0; a < markers.length; a++) {
                      var markerIcon = markers[a].getIcon()
                      if (markerIcon.bean !== undefined) {
                        if (markerIcon.bean.orderCode === data[x].orderCode) {
                          markerIcon.imageUrl = blueIcon
                          markers[a].setIcon(markerIcon)
                        }
                      }
                    }
                  }
                }
              }
            }
            break
          }
          // eslint-disable-next-line no-undef
          clearAll()
          // console.log(overlays[0].Wu.getNorthEast())
        }
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.orgId = value.orgId
        this.currentOrg = value
        this.getOwnerList()
      },
      // 选中站点
      async chooseOrg(value) {
        this.chooseOrgId = value
        // 查询站点围栏和下面的子围栏
        await selectUserFence({ orgId: value }).then(res => {
          if (res.data) {
            this.fenceData = []
            this.fenceData1 = []
            this.fenceData = res.data.filter(item => {
              if (item.fenceType === 1) {
                item.showDetail = false
                item.path = JSON.parse(item.coordinates)
                const options = {
                  strokeColor: item.borderColor, // 边线颜色。
                  fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
                  strokeWeight: 5, // 边线的宽度，以像素为单位。
                  strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
                  fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
                  strokeStyle: 'dashed' // 边线的样式，solid或dashed。
                }
                const ps = []
                for (var i in item.path) {
                  // eslint-disable-next-line no-undef
                  ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
                }
                // eslint-disable-next-line no-undef
                const polygon = new BMap.Polygon(ps, options) // 创建多边形
                item.polygon = polygon
                this.map.addOverlay(polygon)
                // eslint-disable-next-line no-undef
                this.map.centerAndZoom(new BMap.Point(item.lon, item.lat), 15)
                item.position = { lng: item.lon, lat: item.lat }
                return item
              }
            })
            this.fenceData1 = res.data.filter(item => {
              if (item.fenceType === 2) {
                item.path = JSON.parse(item.coordinates)
                const options = {
                  strokeColor: item.borderColor, // 边线颜色。
                  fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
                  strokeWeight: 5, // 边线的宽度，以像素为单位。
                  strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
                  fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
                  strokeStyle: 'dashed' // 边线的样式，solid或dashed。
                }
                const ps = []
                for (var i in item.path) {
                  // eslint-disable-next-line no-undef
                  ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
                }
                // eslint-disable-next-line no-undef
                const polygon = new BMap.Polygon(ps, options) // 创建多边形
                item.polygon = polygon
                item.isOpen = item.isOpen === 1
                this.map.addOverlay(polygon)
                // eslint-disable-next-line no-undef
                this.map.centerAndZoom(new BMap.Point(item.lon, item.lat), 15)
                item.position = { lng: item.lon, lat: item.lat }
                return item
              }
            })
          // console.log(this.fenceData)
          // console.log(this.fenceData1)
          }
        }).catch(err => {
          console.log(err)
          this.fenceData = []
          this.fenceData1 = []
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      // 导出
      async exportFile() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.mapParams
          exportOrderAutoDispatch({
            paramInfo: params,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }

</script>
<style lang='scss' scoped>
.btnInfo {
  display: flex;
  margin-left: 20px;
  font-size: 14px;
  // height:20px;
  img {
    width: 15px;
    height: 20px;
  }
  span {
    margin-right: 8px;
    line-height: 20px;
    text-align: center;
  }
  .btn {
    flex: 1;
  }
}
.left {
  position: relative;
  .name-box {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 1200;
  }
}

/* 隐藏百度图片Logo */
/deep/ .BMap_cpyCtrl {
  display: none;
}
/deep/ .anchorBL {
  display: none;
}
</style>
